import { useCallback } from 'react';
import { message } from 'antd';
import api from '../api/axios';
import { PublishState } from '../types/news';
import { useSelector } from 'react-redux';
import { RootState } from '../store';

/**
 * 新闻发布管理钩子
 * 提供新闻发布、下线和删除等功能
 */
const usePublish = () => {
  // 从Redux获取当前用户信息
  const currentUser = useSelector((state: RootState) => state.user.userInfo);
  
  /**
   * 发布新闻
   * @param id 新闻ID
   * @returns 操作结果Promise
   */
  const publishNews = useCallback(async (id: number | string) => {
    try {
      // 打印详细日志以便调试
      console.log(`准备发布新闻，ID: ${id}`);
      
      // 发送正确的状态值给后端
      await api.patch(`/news/seq/${id}/publish`, {
        // 明确指定publishState为已发布状态(2)
        publishState: PublishState.PUBLISHED, // 值为2，对应后端的已发布状态
        publishTime: Date.now()
      });
      
      message.success('发布成功');
      return true;
    } catch (err) {
      message.error('发布失败');
      console.error('发布新闻失败:', err);
      return false;
    }
  }, []);
  
  /**
   * 下线新闻
   * @param id 新闻ID
   * @returns 操作结果Promise
   */
  const sunsetNews = useCallback(async (id: number | string) => {
    try {
      console.log(`准备下线新闻，ID: ${id}`);
      
      await api.patch(`/news/seq/${id}/sunset`, {
        // 明确指定publishState为已下线状态(3)
        publishState: PublishState.SUNSET, // 值为3，对应后端的已下线状态
        updateTime: Date.now()
      });
      message.success('下线成功');
      return true;
    } catch (err) {
      message.error('下线失败');
      console.error('下线新闻失败:', err);
      return false;
    }
  }, []);
  
  /**
   * 删除新闻
   * @param id 新闻ID
   * @returns 操作结果Promise
   */
  const deleteNews = useCallback(async (id: number | string) => {
    try {
      console.log(`准备删除新闻，ID: ${id}`);
      
      // 先通过seqId获取新闻详情
      const response = await api.get(`/news`, {
        params: {
          seqId: id
        }
      });
      
      // 从返回数据中获取MongoDB的id
      const newsData = response.data?.data;
      if (!newsData || !newsData.length || !newsData[0].id) {
        message.error('未找到新闻数据');
        return false;
      }
      
      const mongoId = newsData[0].id;
      console.log(`找到新闻MongoDB ID: ${mongoId}，准备删除`);
      
      // 使用MongoDB的id删除新闻
      await api.delete(`/news/${mongoId}`);
      
      message.success('删除成功');
      return true;
    } catch (err) {
      message.error('删除失败');
      console.error('删除新闻失败:', err);
      return false;
    }
  }, []);
  
  /**
   * 获取待发布新闻列表
   * @returns 新闻列表和加载状态
   */
  const getUnpublishedNews = useCallback(async () => {
    try {
      const response = await api.get(`/news`, { 
        params: { 
          auditState: 2, 
          publishState: PublishState.PENDING // 修改为PENDING(值为1)，而不是UNPUBLISHED(值为0)
        } 
      });
      return response.data?.data || [];
    } catch (err) {
      console.error('获取待发布新闻失败:', err);
      return [];
    }
  }, []);
  
  /**
   * 获取已发布新闻列表
   * @returns 新闻列表
   */
  const getPublishedNews = useCallback(async () => {
    try {
      const response = await api.get(`/news`, { 
        params: { 
          publishState: PublishState.PUBLISHED 
        } 
      });
      return response.data?.data || [];
    } catch (err) {
      console.error('获取已发布新闻失败:', err);
      return [];
    }
  }, []);
  
  /**
   * 获取已下线新闻列表
   * @returns 新闻列表
   */
  const getSunsetNews = useCallback(async () => {
    try {
      const response = await api.get(`/news`, { 
        params: { 
          publishState: PublishState.SUNSET 
        } 
      });
      return response.data?.data || [];
    } catch (err) {
      console.error('获取已下线新闻失败:', err);
      return [];
    }
  }, []);
  
  /**
   * 获取当前用户的待发布新闻
   */
  const getUserUnpublishedNews = useCallback(async () => {
    if (!currentUser?.username) return [];
    
    try {
      const response = await api.get(`/news`, { 
        params: { 
          auditState: 2, 
          publishState: PublishState.UNPUBLISHED, 
          author: currentUser.username 
        } 
      });
      return response.data?.data || [];
    } catch (err) {
      console.error('获取用户待发布新闻失败:', err);
      return [];
    }
  }, [currentUser]);
  
  /**
   * 获取当前用户的已发布新闻
   */
  const getUserPublishedNews = useCallback(async () => {
    if (!currentUser?.username) return [];
    
    try {
      const response = await api.get(`/news`, { 
        params: { 
          publishState: PublishState.PUBLISHED, 
          author: currentUser.username 
        } 
      });
      return response.data?.data || [];
    } catch (err) {
      console.error('获取用户已发布新闻失败:', err);
      return [];
    }
  }, [currentUser]);
  
  /**
   * 获取当前用户的已下线新闻
   */
  const getUserSunsetNews = useCallback(async () => {
    if (!currentUser?.username) return [];
    
    try {
      const response = await api.get(`/news`, { 
        params: { 
          publishState: PublishState.SUNSET, 
          author: currentUser.username 
        } 
      });
      return response.data?.data || [];
    } catch (err) {
      console.error('获取用户已下线新闻失败:', err);
      return [];
    }
  }, [currentUser]);
  
  return {
    publishNews,
    sunsetNews,
    deleteNews,
    getUnpublishedNews,
    getPublishedNews,
    getSunsetNews,
    getUserUnpublishedNews,
    getUserPublishedNews,
    getUserSunsetNews
  };
};

export default usePublish; 